package system.imp;

import java.io.File;
import java.io.IOException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.DiskFileUpload;
import org.apache.commons.fileupload.FileItem;

import com.hitrust.gs.dao.GSManufactureDAO;
import com.hitrust.gs.lib.GSSystemConfigurator;

public class ProductPictureUploadServlet extends javax.servlet.http.HttpServlet {
	public ProductPictureUploadServlet() {
		super();
	}

	public void init() throws ServletException {
	}

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws javax.servlet.ServletException, java.io.IOException {
	
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws javax.servlet.ServletException, java.io.IOException {
		String type = (String) request.getParameter("type");
		if ("1".equals(type)) {
			uploadDefaultPicture(request, response);
		} else {
			performTask(request, response);
		}
	}

	/*
	 * public static boolean delAllFile(String path) { boolean flag = false;
	 * File file = new File(path); if (!file.exists()) { return flag; } if
	 * (!file.isDirectory()) { return flag; } String[] tempList = file.list();
	 * File temp = null; for (int i = 0; i < tempList.length; i++) { if
	 * (path.endsWith(File.separator)) { temp = new File(path + tempList[i]); }
	 * else { temp = new File(path + File.separator + tempList[i]); } if
	 * (temp.isFile()) { temp.delete(); flag = true; } if (temp.isDirectory()) {
	 * delAllFile(path + "/" + tempList[i]); flag = true; } } return flag; }
	 */
	/**  
  *   
  */
	private static final long serialVersionUID = 7440302204266787092L;

	public void performTask(HttpServletRequest request,
			HttpServletResponse response) throws IOException, ServletException {
		String productCode = (String) request.getParameter("productCode");
		String path=GSSystemConfigurator.getParam("gs.pic.filePath");
		String savePath = path + productCode + "/";// 保存路径
		String uploadPath = path + productCode + "/"; // 上传路径

		File dirFile = null;
		dirFile = new File(savePath);
		if (!(dirFile.exists()) && !(dirFile.isDirectory())) {
			boolean creadoc = dirFile.mkdirs();
			if (creadoc) {
				System.out.println("OK,创建文件夹成功！");
			} else {
				System.out.println("ERROR,创建文件夹失败！");
			}
		}

		try {
			System.out.println("开始进行文件上传");
			DiskFileUpload fu = new DiskFileUpload();
			fu.setSizeMax(4194304); //
			fu.setSizeThreshold(4096); //
			fu.setRepositoryPath(uploadPath); //
			List fileItems = fu.parseRequest(request);

			String nameBefore = getMaxFileName(savePath);
			boolean flags=false;
			for (int i = 0; i < fileItems.size(); i++) {
				FileItem fi = (FileItem) fileItems.get(i);
				String fileName = fi.getName();//
				String[] fname = fileName.split("\\\\");
				String picname = "";
				for (int k = 0; k < fname.length; k++) {
					picname = (String) fname[k];
				}
				if (fileName != null) {
					if (picname.toLowerCase().endsWith(".jpg")) {
						
					}else{
						flags=true;
						response.setContentType("text/html;charset=GBK");
						System.out.println("图片必须为jpg格式!");
						response.getWriter().print("{'success':false,'message':'图片必须为jpg格式!'}");
					}
				}
				
				if(fi.getSize()>1000000){
					flags=true;
					response.setContentType("text/html;charset=GBK");
					System.out.println("图片太大,无法上传!");
					response.getWriter().print("{'success':false,'message':'图片太大,无法上传'}");
				}
			}
			if(flags)
				return;

			for (int i = 0; i < fileItems.size(); i++) {
				FileItem fi = (FileItem) fileItems.get(i);
				String fileName = fi.getName();//
				String[] fname = fileName.split("\\\\");
				String picname = "";
				for (int k = 0; k < fname.length; k++) {
					picname = (String) fname[k];
				}
				if (fileName != null) {
					if (picname.toLowerCase().endsWith(".jpg")) {
						String name = Integer.parseInt(nameBefore) + ".jpg";
						fi.write(new File(savePath + name));
					}
					if (picname.toLowerCase().endsWith(".gif")) {
						String name = Integer.parseInt(nameBefore) + ".gif";
						fi.write(new File(savePath + name));
					}
					if (picname.toLowerCase().endsWith(".bmp")) {
						String name = Integer.parseInt(nameBefore) + ".bmp";
						fi.write(new File(savePath + name));
					}
					if (picname.toLowerCase().endsWith(".png")) {
						String name = Integer.parseInt(nameBefore) + ".png";
						fi.write(new File(savePath + name));
					}
				}

			}
			GSManufactureDAO manuDao=new GSManufactureDAO();
			boolean flag=manuDao.getProductPictureByConcentricityCode(productCode);
			if(!flag){
				manuDao.insertProductPicture(productCode);
			}
			response.setContentType("text/html;charset=GBK");
			System.out.println("上传成功");
			response.getWriter().print("{'success':true,'message':'上传成功'}");
		} catch (Exception e) {
			System.out.println("上传失败");
			response.getWriter().print("{'success':false,'message':'上传失败'}");
		}
	}

	public static String getMaxFileName(String path) {
		File file = new File(path);
		if (!file.exists()) {
			return "error";
		}
		if (!file.isDirectory()) {
			return "error";
		}
		String[] tempList = file.list();

		if (tempList.length == 0) {
			return "10000";
		}

		int max = 10000;
		for (int i = 0; i < tempList.length; i++) {
			if (path.endsWith(File.separator)) {
				if (".jpg".equalsIgnoreCase(tempList[i].substring(
						tempList[i].length() - 4, tempList[i].length()))
						|| ".gif"
								.equalsIgnoreCase(tempList[i].substring(
										tempList[i].length() - 4,
										tempList[i].length()))
						|| ".bmp"
								.equalsIgnoreCase(tempList[i].substring(
										tempList[i].length() - 4,
										tempList[i].length()))
						|| ".png"
								.equalsIgnoreCase(tempList[i].substring(
										tempList[i].length() - 4,
										tempList[i].length()))) {
					String names = tempList[i].substring(0,
							tempList[i].length() - 4);
					if (Integer.parseInt(names) >= max) {
						max = Integer.parseInt(names);
					}

				}
			} else {
				if (".jpg".equalsIgnoreCase(tempList[i].substring(
						tempList[i].length() - 4, tempList[i].length()))
						|| ".gif"
								.equalsIgnoreCase(tempList[i].substring(
										tempList[i].length() - 4,
										tempList[i].length()))
						|| ".bmp"
								.equalsIgnoreCase(tempList[i].substring(
										tempList[i].length() - 4,
										tempList[i].length()))
						|| ".png"
								.equalsIgnoreCase(tempList[i].substring(
										tempList[i].length() - 4,
										tempList[i].length()))) {
					String names = tempList[i].substring(0,
							tempList[i].length() - 4);
					if (Integer.parseInt(names) >= max) {
						max = Integer.parseInt(names);
					}

				}
			}
		}
		max = max + 1;
		return max + "";
	}

	public void uploadDefaultPicture(HttpServletRequest request,
			HttpServletResponse response) throws IOException, ServletException {
		String productCode = (String) request.getParameter("productCode");
		String path=GSSystemConfigurator.getParam("gs.pic.filePath");
		String savePath = path + productCode + "/";// 保存路径
		String uploadPath = path + productCode + "/"; // 上传路径

		File dirFile = null;
		dirFile = new File(savePath);
		if (!(dirFile.exists()) && !(dirFile.isDirectory())) {
			boolean creadoc = dirFile.mkdirs();
			if (creadoc) {
				System.out.println("OK,创建文件夹成功！");
			} else {
				System.out.println("ERROR,创建文件夹失败！");
			}
		}
		
		try {
			System.out.println("开始进行文件上传");
			DiskFileUpload fu = new DiskFileUpload();
			fu.setSizeMax(4194304); //
			fu.setSizeThreshold(4096); //
			fu.setRepositoryPath(uploadPath); //
			List fileItems = fu.parseRequest(request);

			String nameBefore = getMinFileName(savePath);
			boolean flags=false;
			for (int i = 0; i < fileItems.size(); i++) {
				FileItem fi = (FileItem) fileItems.get(i);
				String fileName = fi.getName();//
				String[] fname = fileName.split("\\\\");
				String picname = "";
				for (int k = 0; k < fname.length; k++) {
					picname = (String) fname[k];
				}
				if (fileName != null) {
					if (picname.toLowerCase().endsWith(".jpg")) {
						
					}else{
						flags=true;
						response.setContentType("text/html;charset=GBK");
						System.out.println("图片必须为jpg格式!");
						response.getWriter().print("{'success':false,'message':'图片必须为jpg格式!'}");
					}
				}
				

				if(fi.getSize()>1000000){
					response.setContentType("text/html;charset=GBK");
					System.out.println("图片太大,无法上传!");
					response.getWriter().print("{'success':false,'message':'图片太大,无法上传'}");
				}
			}
			if(flags)
				return;
			
			for (int i = 0; i < fileItems.size(); i++) {
				FileItem fi = (FileItem) fileItems.get(i);
				String fileName = fi.getName();//
				String[] fname = fileName.split("\\\\");
				String picname = "";
				for (int k = 0; k < fname.length; k++) {
					picname = (String) fname[k];
				}

				if (fileName != null) {
					if (picname.toLowerCase().endsWith(".jpg")) {
						String name = Integer.parseInt(nameBefore) + ".jpg";
						fi.write(new File(savePath + name));
					}
					if (picname.toLowerCase().endsWith(".gif")) {
						String name = Integer.parseInt(nameBefore) + ".gif";
						fi.write(new File(savePath + name));
					}
					if (picname.toLowerCase().endsWith(".bmp")) {
						String name = Integer.parseInt(nameBefore) + ".bmp";
						fi.write(new File(savePath + name));
					}
					if (picname.toLowerCase().endsWith(".png")) {
						String name = Integer.parseInt(nameBefore) + ".png";
						fi.write(new File(savePath + name));
					}
				}

			}
			
			GSManufactureDAO manuDao=new GSManufactureDAO();
			boolean flag=manuDao.getProductPictureByConcentricityCode(productCode);
			if(!flag){
				manuDao.insertProductPicture(productCode);
			}

			response.setContentType("text/html;charset=GBK");
			System.out.println("上传成功");
			response.getWriter().print("{'success':true,'message':'上传成功'}");
		} catch (Exception e) {
			System.out.println("上传失败");
			response.getWriter().print("{'success':false,'message':'上传失败'}");
		}
	}

	public static String getMinFileName(String path) {
		File file = new File(path);
		if (!file.exists()) {
			return "error";
		}
		if (!file.isDirectory()) {
			return "error";
		}
		String[] tempList = file.list();

		if (tempList.length == 0) {
			return "10000";
		}
	
		int min = 10000;
		for (int i = 0; i < tempList.length; i++) {
			if (path.endsWith(File.separator)) {
				if (".jpg".equalsIgnoreCase(tempList[i].substring(
						tempList[i].length() - 4, tempList[i].length()))
						|| ".gif"
								.equalsIgnoreCase(tempList[i].substring(
										tempList[i].length() - 4,
										tempList[i].length()))
						|| ".bmp"
								.equalsIgnoreCase(tempList[i].substring(
										tempList[i].length() - 4,
										tempList[i].length()))
						|| ".png"
								.equalsIgnoreCase(tempList[i].substring(
										tempList[i].length() - 4,
										tempList[i].length()))) {
					String names = tempList[i].substring(0,
							tempList[i].length() - 4);
					if (Integer.parseInt(names) <= min) {
						min = Integer.parseInt(names);
					}

				}
			} else {
				if (".jpg".equalsIgnoreCase(tempList[i].substring(
						tempList[i].length() - 4, tempList[i].length()))
						|| ".gif"
								.equalsIgnoreCase(tempList[i].substring(
										tempList[i].length() - 4,
										tempList[i].length()))
						|| ".bmp"
								.equalsIgnoreCase(tempList[i].substring(
										tempList[i].length() - 4,
										tempList[i].length()))
						|| ".png"
								.equalsIgnoreCase(tempList[i].substring(
										tempList[i].length() - 4,
										tempList[i].length()))) {
					String names = tempList[i].substring(0,
							tempList[i].length() - 4);
					if (Integer.parseInt(names) <= min) {
						min = Integer.parseInt(names);
					}

				}
			}
		}
		min = min - 1;
		return min + "";
	}

}
